/*
 * Copyright @ 2025 weili23
 * com.example.ai 17:39
 * All right reserved.
 */

package com.example.ai;

import jdk.nashorn.internal.AssertsEnabled;
import org.elasticsearch.action.search.*;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

/**
 * @desc: 深分页查询
 * @author: weili23
 * @createTime: 2025/8/15 17:39
 * @version: v1.0
 */
@SpringBootTest
public class ScrollSearch {
    public static final String INDEX_NAME = "person";
    @Resource
    private RestHighLevelClient client;

    @Test
    void scrollSearch() throws Exception {
        //1.构建查询
        SearchRequest request = new SearchRequest(INDEX_NAME);
        //指定ES生存周期 设置1min
        request.scroll(TimeValue.timeValueMinutes(1L));
        //构建请求条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        sourceBuilder.size(2); //每次查询两条
        request.source(sourceBuilder);
        //发送请求
        SearchResponse search = client.search(request, RequestOptions.DEFAULT);
        String scrollId = search.getScrollId();
        SearchHit[] hits = search.getHits().getHits();
        System.out.println("=============第一次查询出来的结果=========");
        for (SearchHit hit : hits){
            System.out.println(hit.getSourceAsString());
        }

        while (true){
            //继续下一次查询  用第一次返回的scrollid
            SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
            scrollRequest.scroll(TimeValue.timeValueMinutes(1L));
            //scrollRequest.scrollId(scrollId);
            SearchResponse scrollResponse = client.scroll(scrollRequest, RequestOptions.DEFAULT);
            SearchHit[] hits1 = scrollResponse.getHits().getHits();
            if (hits1 == null || hits1.length == 0) {
                System.out.println("没有更多数据了");
                break;
            }
            System.out.println("=============下一次查询=============");
            for (SearchHit hit : hits1) {
                System.out.println(hit.getSourceAsString());
            }
        }

        //最后清除es上下文
        ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
        clearScrollRequest.addScrollId(scrollId);
        ClearScrollResponse clearScrollResponse = client.clearScroll(clearScrollRequest, RequestOptions.DEFAULT);
        boolean succeeded = clearScrollResponse.isSucceeded();
        System.out.println("===清理es上下文====:"+succeeded);


    }

}
